﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace JWTDemo
{
    public class JwtManager
    {
        public string CreatJwtToken()
        {
            //签名密钥
            string jwtKey = "chuangqianmingyueguang";
            //签发者
            string jwtIssuser = "jiaheshangqianfa";
            //接收者
            string jwtAudience = "jiaheshangjieshou";
            //令牌所承载的信息
            var claims = new[]
            {
                //用户Id
                new Claim("Id","userId"),
                new Claim("Name","userName"),
                new Claim("Role","userRole")
            };
            //获取对称密钥
            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtKey));
            //使用has256加密密钥
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //生成token
            var token = new JwtSecurityToken(
                //签发者
                jwtIssuser,
                //接收者
                jwtAudience,
                //jwt令牌数据体
                claims: claims,
                //令牌过期时间
                expires: DateTime.Now.AddMinutes(10),
                //为数字签名定义SecurityKey
                signingCredentials: creds
                );
            return "Bearer " + new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}